package com.bw.aop;

import com.alibaba.fastjson.JSON;
import com.bw.entity.LoginUser;
import com.bw.entity.SysLog;
import com.bw.mapper.SysLogMapper;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@Component
@Slf4j
@Aspect
public class LogAspect {

    @Autowired
    HttpServletRequest request;
    @Autowired
    SysLogMapper sysLogMapper;

    @AfterReturning(pointcut = "@annotation(controllerLog)", returning = "jsonResult")
    public void doAfterReturning(JoinPoint joinPoint, MyLog
            controllerLog, Object jsonResult) {
        try {
            SysLog logs = new SysLog();
// 获取当前的用户
            LoginUser loginUser = (LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();

            logs.setUserId(loginUser.getId().intValue());
            logs.setUserName(loginUser.getUsername());

// 设置方法名称
            String className =
                    joinPoint.getTarget().getClass().getName();
            String methodName = joinPoint.getSignature().getName();
            logs.setMethod(className + "." + methodName + "()");
            // 设置请求参数
            logs.setArgs(JSON.toJSONString(joinPoint.getArgs()));
            // 设置请求地址
            logs.setUrl(request.getRequestURI());
            // 操作详情
            String ops = controllerLog.ops();
            logs.setOps(ops);
            logs.setCreateTime(new Date());
            //  保存数据库
            sysLogMapper.insert(logs);
        } catch (Exception exp) {
            // 记录本地异常日志
            log.error("==通知异常==");
            log.error("异常信息:{}", exp.getMessage());
            exp.printStackTrace();
        }
    }

}
